## -*- coding: utf-8 -*-

#   Copyright (C) 2007, 2008 Yves Junqueira (yves@cetico.org) 
#
#    This file is part of GeekDNS.
#
#    GeekDNS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    GeekDNS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with GeekDNS.  If not, see <http://www.gnu.org/licenses/>.

from turbogears import widgets, validators, identity
from geekroot import register_model
from kid import XML
from turbogears.i18n.data import pt_BR

UF_BR = ['--', 'AC','AL','AM','AP','BA','CE','DF','ES','GO','MA','MG','MS','MT','PA','PB',
    'PE','PI','PR','RJ','RN','RO','RR','RS','SC','SE','SP','TO',
              '--']

countries = pt_BR.countries.values()
countries.sort()

class FakeInputWidget(widgets.Widget):
  "Simple widget that allows displaying its value in a span."
  
  params = ["field_class", "css_classes"]
  params_doc = {'field_class' : 'CSS class for the field',
          'css_classes' : 'List of extra CSS classes for the field'}
  field_class = None
  css_classes = []
  
  def __init__(self, name=None, label=None, **kw):
    super(FakeInputWidget, self).__init__(name, **kw)
    self.label = label
    self.validator = None
    self.help_text = None
    
  template = """
    <span xmlns:py="http://purl.org/kid/ns#" 
      class="${field_class}" 
      py:content="value" />
    """

class NewUserFields(widgets.WidgetsList):
  
  email = widgets.TextField('email',
          label=_("Email*"),
          help_text=u"Seu endereço de e-mail (será validado).")
          
  email_2 = widgets.TextField('email2',
          label="Email (novamente)*",
          help_text=u"Repita seu endereço de e-mail, por favor.")
  
  full_name = widgets.TextField('full_name',
          "Nome completo*",
          help_text=_("Seu nome completo, sem siglas."))
          
  password_1 = widgets.PasswordField('password1',
          label=_("Senha*"),
          help_text=_("Escolha uma senha."))
          
  password_2 = widgets.PasswordField('password2',
          label= _("Senha (novamente)*"),
          help_text=_("Repita a senha."))
          
  street_address = widgets.TextField('street_address',
          label=u'Endereço*',
          help_text=u'Endereço completo para correspondências.')

  city = widgets.TextField('city',
          label="Cidade*",
           )
  
  state = widgets.SingleSelectField('state',
          label=u'Estado*',
          options = UF_BR
          )
  country = widgets.SingleSelectField('country',
          label=u'País*',
          options = countries,
          default = 'Brasil'
          )
  zipcode = widgets.TextField('zipcode',
          label="CEP*",
          help_text=XML('<a\
          href="http://www.correios.com.br/servicos/cep/" \
          target="_new">Busca</a>')
          )
  phone1 = widgets.TextField('phone1',
          label=u'Telefone*',
          help_text=u'Telefone incluíndo DDD',
          )
  phone2 = widgets.TextField('phone2',
          label=u'Telefone 2',
          help_text=u'Telefone incluíndo DDD (opcional)\
          (ex: seu telefone residencial)',
          )
  mobilephone = widgets.TextField('mobilephone',
          label=u'Celular',
          help_text=u'Celular incluíndo DDD (opcional)',
          )
  homepage = widgets.TextField('homepage',
          label=u'Home-page',
          help_text=u'Endereço do site atual (opcional)',
          )

class ExistingUserFields(widgets.WidgetsList):
  
  email = widgets.TextField('email',
          label=_("Email*"),
          help_text=u"Seu endereço de e-mail (será validado).")
          
  full_name = widgets.TextField('full_name',
          "Nome completo*",
          help_text=_("Seu nome completo, sem siglas."))
          
  old_password = widgets.PasswordField('old_password',
           label=_("Current password"),
           help_text=_("The current (old) password."))

  password_1 = widgets.PasswordField('password1',
          label=_("New Password"),
          help_text=_("Your new password. (If you would like to change it)."))

  password_2 = widgets.PasswordField('password2',
          label=_("New Password (again)"),
          help_text=_("New password again (should match the input above)."))

  street_address = widgets.TextField('street_address',
          label=u'Endereço*',
          help_text=u'Endereço completo para correspondências.')

  city = widgets.TextField('city',
          label="Cidade*",
           )
  
  state = widgets.SingleSelectField('state',
          label=u'Estado*',
          options = UF_BR
          )
  country = widgets.SingleSelectField('country',
          label=u'País*',
          options = countries,
          default = 'Brasil'
          )
  zipcode = widgets.TextField('zipcode',
          label="CEP*",
          help_text=XML('<a\
          href="http://www.correios.com.br/servicos/cep/" \
          target="_new">Busca</a>')
          )
  phone1 = widgets.TextField('phone1',
          label=u'Telefone*',
          help_text=u'Telefone incluíndo DDD',
          )
  phone2 = widgets.TextField('phone2',
          label=u'Telefone 2',
          help_text=u'Telefone incluíndo DDD (opcional)\
          (ex: seu telefone residencial)',
          )
  mobilephone = widgets.TextField('mobilephone',
          label=u'Celular',
          help_text=u'Celular incluíndo DDD (opcional)',
          )
  homepage = widgets.TextField('homepage',
          label=u'Home-page',
          help_text=u'Endereço do site atual (opcional)',
          )

class UniqueEmail(validators.FancyValidator):
  "Validator to confirm a given email address is unique."
  messages = {'notUnique': u'Este endereço já está registrado por\
  outro usuário'}
  
  def _to_python(self, value, state):
    if identity.not_anonymous():
      if value == identity.current.user.email_address:
        # the user isn't trying to change their email address
        # so the value is ok
        return value 
    if not register_model.email_is_unique(value):
      raise validators.Invalid(self.message('notUnique', state), value, state)
    return value
    
class ValidPassword(validators.FancyValidator):
  """Validator to test for validity of password.
  """

  messages = {'invalid': u'A senha fornecida é inválida.'}

  def validate_python(self, value, state):
    user = identity.current.user
    if not identity.current_provider.validate_password(user,
    user.email_address, value):
      raise validators.Invalid(
        self.message('invalid', state), value, state)
    return value
    
class NewUserSchema(validators.Schema):  
  email = validators.All(validators.Email(not_empty=True, max=255),
                UniqueEmail())
  email2 = validators.All(validators.Email(not_empty=True, max=255))
  full_name = validators.UnicodeString(not_empty=True, strip=True, max=255)
  password1 = validators.UnicodeString(not_empty=True, max=40)
  password2 = validators.UnicodeString(not_empty=True, max=40)
  chained_validators = [validators.FieldsMatch('password1', 'password2'),
              validators.FieldsMatch('email', 'email2')]
  street_address = validators.UnicodeString(not_empty=True, max=255)
  city = validators.UnicodeString(not_empty=True)
  state = validators.OneOf(UF_BR)
  country = validators.OneOf(countries)
  zipcode = validators.UnicodeString(not_empty=True, min=8, max=9)
  phone1 = validators.UnicodeString(not_empty=True, min=7)

class ExistingUserSchema(validators.Schema):
  email = validators.All(validators.Email(not_empty=True, max=255),
                UniqueEmail())
  full_name = validators.UnicodeString(not_empty=True, strip=True, max=255)
  old_password = validators.All(validators.UnicodeString(max=40),
                  ValidPassword())
  password1 = validators.UnicodeString(max=40)
  password2 = validators.UnicodeString(max=40)
  chained_validators = [validators.FieldsMatch('password1', 'password2')]
  street_address = validators.UnicodeString(not_empty=True, max=255)
  city = validators.UnicodeString(not_empty=True)
  state = validators.UnicodeString(not_empty=True, max=2)
  country = validators.UnicodeString(not_empty=True)
  zipcode = validators.UnicodeString(not_empty=True, min=8, max=9)
  phone1 = validators.UnicodeString(not_empty=True, min=7)

class RegTableForm(widgets.TableForm):
  template = 'geekroot.templates.register_tabletemplate'
  
lost_password_form = RegTableForm( fields = [
                      widgets.TextField('email_or_username',
                      label='User Name or Email Address',
                      validator=validators.UnicodeString(not_empty=True, max=255)) ]
                    )
      
